package com.example.springboot2.interceptor;

import com.example.springboot2.CommonHelper.RedisHelper;
import com.example.springboot2.Service.Sys_UserService;
import com.example.springboot2.myannotation.NoAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthorizationInterceptor implements org.springframework.web.servlet.AsyncHandlerInterceptor {

    @Resource
    private RedisHelper redisHelper=new RedisHelper();

    public static final String USER_KEY = "userId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //设置跨域--开始
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        setHeader(httpRequest,httpResponse);
        //设置跨域--结束

        NoAuth annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(NoAuth.class);
        }else{
            return true;
        }

        if(annotation != null){
            return true;
        }

        //从header中获取token
        String token = request.getHeader("token");
        Object user=redisHelper.get(token);
        if(user==null)
        {
            return false;
        }
        else
        {
            return true;
        }
        //查询token信息
//        TokenEntity tokenEntity = tokenService.getByToken(token);
//        if(tokenEntity == null || tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()){
//            throw new RenException(ErrorCode.TOKEN_INVALID);
//        }
//
//        //设置userId到request里，后续根据userId，获取用户信息
//        request.setAttribute(USER_KEY, tokenEntity.getUserId());
    }

    /**
     * 为response设置header，实现跨域
     */
    private void setHeader(HttpServletRequest request, HttpServletResponse response){
        //跨域的header设置
        response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", request.getMethod());
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
        //防止乱码，适用于传输JSON数据
        response.setHeader("Content-Type","application/json;charset=UTF-8");
    }

}
